package com.example.controller;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/redission")
public class RedissionController {


    @Resource
    private RedissonClient redissonClient;

    @RequestMapping("/lock1")
    public String lock1(){
        String uId = UUID.randomUUID().toString();
        RLock lock = redissonClient.getLock("lock" + uId);
        try {
            lock.lock();
            System.out.println("lock id is " + uId);
            Thread.sleep(5 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return uId;
    }

    @RequestMapping("/lock2")
    public String lock2(){
        String uId = UUID.randomUUID().toString();
        RLock lock = redissonClient.getLock("lock" + uId);
        try {
            //8s后解锁
            lock.lock(10, TimeUnit.SECONDS);
            System.out.println("lock id is " + uId);
            Thread.sleep(8 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return uId;
    }

    @RequestMapping("/lock3")
    public String lock3(){
        String uId = UUID.randomUUID().toString();
        RLock lock = redissonClient.getLock("lock" + uId);
        try {
            // 尝试加锁，最多等待100秒，上锁以后10秒自动解锁
            boolean res = lock.tryLock(100, 10, TimeUnit.SECONDS);
            if (res){
                try {
                    Thread.sleep(8 * 1000);
                    System.out.println("lock id is " + uId);
                } finally {
                    lock.unlock();
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return uId;
    }

}
